const {
	sha256,
	getHash,
	getDate
} = require('./request-utils')

function setRequest(url, method, header, data) {
	const promise = new Promise((resolve, reject) => {
		const that = this;
		uni.request({
			url: url,
			data,
			method,
			dataType: "json",
			header,
			success: function(res) {
				resolve(res);
			},
			fail: function(e) {
				reject("网络出错,连接失败！" + JSON.stringify(e));
			}
		});
	});
	return promise;
}

const postRequest = function(url, data, options) {
	// 参数校验
	const {
		endpoint,
		service,
		region,
		action,
		version
	} = options;
	
	if (endpoint === undefined || service === undefined || region === undefined ||
		action === undefined || version === undefined) {
		console.error("参数错误");
		return
	}
	
	// 设置header
	// 获取参数
	const BASE_URL = process.uniEnv.BASE_URL;
	const SECRET_ID = process.uniEnv.TENCENTCLOUD_SECRET_ID;
	const SECRET_KEY = process.uniEnv.TENCENTCLOUD_SECRET_KEY;

	const timestamp = Math.floor(new Date().getTime() / 1000);
	//时间处理, 获取世界时间日期
    const date = getDate(timestamp)
	
	// ************* 步骤 1：拼接规范请求串 *************
	data = JSON.stringify(data)
	const hashedRequestPayload = getHash(data);
	const httpRequestMethod = "POST"
	const canonicalUri = "/"
	const canonicalQueryString = ""
	
	const canonicalHeaders = "content-type:application/json; charset=utf-8\n" +
		"host:" + endpoint + "\n" +
		"x-tc-action:" + action.toLowerCase() + "\n"
	const signedHeaders = "content-type;host;x-tc-action"
	const canonicalRequest = httpRequestMethod + "\n" +
		canonicalUri + "\n" +
		canonicalQueryString + "\n" +
		canonicalHeaders + "\n" +
		signedHeaders + "\n" +
		hashedRequestPayload
	// console.log("步骤 1：拼接规范请求串",canonicalRequest)

	// ************* 步骤 2：拼接待签名字符串 *************
	const algorithm = "TC3-HMAC-SHA256"
	const hashedCanonicalRequest = getHash(canonicalRequest);
	const credentialScope = date + "/" + service + "/" + "tc3_request"
	const stringToSign = algorithm + "\n" +
		timestamp + "\n" +
		credentialScope + "\n" +
		hashedCanonicalRequest
	// console.log("步骤 2：拼接待签名字符串",stringToSign)

	// ************* 步骤 3：计算签名 *************
	const kDate = sha256(date, 'TC3' + SECRET_KEY)
	const kService = sha256(service, kDate)
	const kSigning = sha256('tc3_request', kService)
	const signature = sha256(stringToSign, kSigning, 'hex')
	// console.log("步骤 3：计算签名",signature)

	// ************* 步骤 4：拼接 Authorization *************
	const authorization = algorithm + " " +
		"Credential=" + SECRET_ID + "/" + credentialScope + ", " +
		"SignedHeaders=" + signedHeaders + ", " +
		"Signature=" + signature
	// console.log("步骤 4：拼接 Authorization",authorization)

	// ************* 步骤 5：设置header *************
	let header = {
		"Authorization": authorization,
		"Content-Type": "application/json; charset=utf-8",
		"Host": endpoint,
		"X-TC-Action": action,
		"X-TC-Timestamp": timestamp.toString(),
		"X-TC-Version": version,
		"X-TC-Region": region
	}
	// console.log("步骤 5：设置header",header)
	// console.log("BASE_URL",BASE_URL + url)
	return setRequest( "https://" + BASE_URL + url, "POST", header, data);
}

module.exports = {
	wxttsPost:postRequest,
};